#!/bin/bash

# Adapted from https://gist.github.com/peterhost/715255
#     If you wish the Daemon to be lauched at boot / stopped at shutdown :
#     INSTALL : update-rc.d scriptname defaults
#     (UNINSTALL : update-rc.d -f  scriptname remove)
#
# Provides:          {{label}}
# Required-Start:    $remote_fs $named $syslog
# Required-Stop:     $remote_fs $named $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: {{servicesummary}}
# Description:       {{servicedescription}}
# Author:            {{author}}
# Created:           {{created}}

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin # modify if needed

DAEMON_ARGS="{{script}}"                # path to your node.js server/app
                                        # NB: don't use ~/ in path

DESC="{{description}}"                  # whatever fancy description you like

NODEUSER={{user}}:{{group}}             # USER who OWNS the daemon process (no matter whoever runs the init script)
                                        # user:group (if no group is specified, the primary GID for that user is used)

LOCAL_VAR_RUN=/var/run                  # In case the init script is run by non-root user, you need to
                                        # indicate a directory writeable by $NODEUSER to store the PID file

DAEMON={{execpath}}                     # this SHOULD POINT TO where your node executable is

LABEL={{label}}
LOGFILE={{logroot}}/$LABEL.log # Logfile path
ERRFILE={{logroot}}/$LABEL-error.log # Error file path


# ______________________________________________________________________________

# Do NOT "set -e"

# Create the log file if it does not exist already
if [ ! -a "{{logroot}}" ];then
  mkdir -p {{logroot}};
fi

if [ ! -a $LOGFILE ];then 
  touch $LOGFILE;
fi

# Create the error log file if it does not exist already
if [ ! -a $ERRFILE ];then 
  touch $ERRFILE;
fi

# Make sure the log and error files are both writable by the target node user
chown $NODEUSER $LOGFILE;
chown $NODEUSER $ERRFILE;


[ $UID -eq "0" ] && LOCAL_VAR_RUN=/var/run # in case this script is run by root, override user setting
THIS_ARG=$0
INIT_SCRIPT_NAME=`basename $THIS_ARG`
[ -h $THIS_ARG ] && INIT_SCRIPT_NAME=`basename $(readlink $THIS_ARG)` # in case of symlink
INIT_SCRIPT_NAME_NOEXT=${INIT_SCRIPT_NAME%.*}
PIDFILE="$LOCAL_VAR_RUN/$INIT_SCRIPT_NAME_NOEXT.pid"
SCRIPTNAME=/etc/init.d/$INIT_SCRIPT_NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] ||  { echo "can't find Node.js ($DAEMON)"  >&2; exit 0; }

# Exit if the 'run' folder is not present
[ -d "$LOCAL_VAR_RUN" ] || { echo "Directory $LOCAL_VAR_RUN does not exist. Modify the '$INIT_SCRIPT_NAME_NOEXT' init.d script ($THIS_ARG) accordingly" >&2; exit 0; }

# Read configuration variable file if it is present
[ -r /etc/default/$INIT_SCRIPT_NAME ] && . /etc/default/$INIT_SCRIPT_NAME

# Load the VERBOSE setting and other rcS variables
[ -r /lib/init/vars.sh ] && . /lib/init/vars.sh

# Define LSB log_* functions.

# To be replaced by LSB functions
# Defined here for distributions that don't define
# log_daemon_msg

log_daemon_msg () {
    echo $@
}

# To be replaced by LSB functions
# Defined here for distributions that don't define
# log_end_msg
log_end_msg () {
    retval=$1
    if [ $retval -eq 0 ]; then
        echo "."
    else
        echo " failed!"
    fi
    return $retval
}

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

# uncomment to override system setting
VERBOSE=yes

# Constructed Variables
USER=`id -n -u`
PIDFILE={{pidroot}}/$INIT_SCRIPT_NAME_NOEXT.pid

#
# Function that starts the daemon/service
#
do_start()
{
  # Return 1 if daemon was already running
  start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid $NODEUSER --background --exec $DAEMON --name $LABEL --test > /dev/null \
    || { [ "$VERBOSE" != no ] && log_daemon_msg  "  --->  Daemon already running $DESC" "$INIT_SCRIPT_NAME_NOEXT"; return 1; }

  # Return 2 if daemon could not be started
  { start-stop-daemon --start --quiet --chuid $NODEUSER --make-pidfile --pidfile $PIDFILE --background --name $LABEL --exec $DAEMON -- \
    $DAEMON_ARGS {{{wrappercode}}} & } \
    || { [ "$VERBOSE" != no ] && log_daemon_msg  "  --->  could not be start $DESC" "$INIT_SCRIPT_NAME_NOEXT"; return 2; }

  # Add code here, if necessary, that waits for the process to be ready
  # to handle requests from services started subsequently which depend
  # on this one.  As a last resort, sleep for some time.
  
  #[ "$VERBOSE" != no ] && log_daemon_msg  "  --->  started $INIT_SCRIPT_NAME_NOEXT"
  # Return 0 when daemon has been started
  return 0;
}

#
# Function that stops the daemon/service
#
do_stop()
{
  # Return
  #   0 if daemon has been stopped
  #   1 if daemon was already stopped
  #   2 if daemon could not be stopped
  #   other if a failure occurred
  
  start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --chuid $NODEUSER --name $LABEL
  RETVAL="$?"
  
  #[ "$VERBOSE" != no ] && [ "$RETVAL" = 1 ] && log_daemon_msg  "  --->  SIGKILL failed => hardkill $DESC" "$INIT_SCRIPT_NAME_NOEXT"
  [ "$RETVAL" = 2 ] && return 2

  # Wait for children to finish too if this is a daemon that forks
  # and if the daemon is only ever run from this initscript.
  # If the above conditions are not satisfied then add some other code
  # that waits for the process to drop all resources that could be
  # needed by services started subsequently.  A last resort is to
  # sleep for some time.
  
  start-stop-daemon --stop --quiet --oknodo --retry=0/3/KILL/5 --pidfile $PIDFILE  --chuid $NODEUSER --exec $DAEMON -- $DAEMON_ARGS {{{wrappercode}}}
  [ "$?" = 2 ] && return 2

  sleep 1
  
  # Kill the child process forcibly
  NODESCRIPT={{{nodescript}}}
  CPID=`pgrep -f $NODESCRIPT`
  kill -9 $CPID 
  
  # Many daemons don't delete their pidfiles when they exit.
  rm -f $PIDFILE

  [ "$VERBOSE" != no ] && [ "$RETVAL" = 1 ] && log_daemon_msg "  --->  $INIT_SCRIPT_NAME_NOEXT - $DESC not running"
  [ "$VERBOSE" != no -a "$RETVAL" = 0 ] && log_daemon_msg "  --->  $INIT_SCRIPT_NAME_NOEXT - $DESC stopped"
  return "$RETVAL"
}

#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
  #
  # If the daemon can reload its configuration without
  # restarting (for example, when it is sent a SIGHUP),
  # then implement that here.
  #
  start-stop-daemon --stop --quiet --signal 1 --pidfile $PIDFILE  --chuid $NODEUSER --name $LABEL
  return 0
}

#
# Function that returns the daemon
#
do_status() {
  #
  # http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
  # 0 program is running or service is OK
  # 1 program is dead and /var/run pid file exists
  # (2 program is dead and /var/lock lock file exists) (not used here)
  # 3 program is not running
  # 4 program or service status is unknown
  RUNNING=$(running)

  ispidactive=$(pidof $NAME | grep `cat $PIDFILE 2>&1` >/dev/null 2>&1)
  ISPIDACTIVE=$?

  if [ -n "$RUNNING" ]; then
    if [ $ISPIDACTIVE ]; then 
      log_success_msg "$INIT_SCRIPT_NAME_NOEXT running (launched by $USER, --chuid $NODEUSER)."
      exit 0
    fi
  else
    if [ -f $PIDFILE ]; then
      rm -f $PIDFILE
      log_success_msg "$INIT_SCRIPT_NAME_NOEXT is not running. Phantom pidfile, $PIDFILE, removed."
      exit 1
    else
      log_success_msg "$INIT_SCRIPT_NAME_NOEXT is not running."
      exit 3
    fi
  fi
}

running() {
  RUNSTAT=$(start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid $NODEUSER --background --exec $DAEMON --test > /dev/null)
  if [ "$?" = 1 ]; then
    echo y
  fi
}

case "$1" in
  start)
  [ "$VERBOSE" != no ] && log_daemon_msg "Starting $INIT_SCRIPT_NAME_NOEXT"
  do_start
  case "$?" in
    0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
    2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
  esac
  ;;
  stop)
  [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $INIT_SCRIPT_NAME_NOEXT"
  do_stop
  case "$?" in
    0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
    2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
  esac
  ;;
  
  reload)
  #
  # If do_reload() is not implemented then leave this commented out
  # and leave 'force-reload' as an alias for 'restart'.
  #
  log_daemon_msg "Reloading $INIT_SCRIPT_NAME_NOEXT"
  do_reload
  log_end_msg $?
  ;;

  restart|force-reload)
 
  #
  # If the "reload" option is implemented then remove the
  # 'force-reload' alias
  #
  log_daemon_msg "Restarting $INIT_SCRIPT_NAME_NOEXT"
  do_stop
  case "$?" in
    0|1)
    do_start
    case "$?" in
      0) log_end_msg 0 ;;
      1) log_end_msg 1 ;; # Old process is still running
      *) log_end_msg 1 ;; # Failed to start
    esac
    ;;
    *)
      # Failed to stop
    log_end_msg 1
    ;;
  esac
  ;;
  status)
    do_status
  ;;
  *)
  echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
  #echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
  exit 3
  ;;
esac

exit 0
